//
//  Country.m
//
//  Created by TuanNT on 5/4/14
//  Copyright (c) 2014 Fsoft. All rights reserved.
//

#import "Country.h"


NSString *const kCountryId = @"id";
NSString *const kCountryTitle = @"title";


@interface Country ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation Country

@synthesize countryId = _countryId;
@synthesize title = _title;


+ (Country *)modelObjectWithDictionary:(NSDictionary *)dict {
	Country *instance = [[Country alloc] initWithDictionary:dict];
	return instance;
}

- (instancetype)initWithDictionary:(NSDictionary *)dict {
	self = [super init];

	// This check serves to make sure that a non-NSDictionary object
	// passed into the model class doesn't break the parsing.
	if (self && [dict isKindOfClass:[NSDictionary class]]) {
		self.countryId = [self objectOrNilForKey:kCountryId fromDictionary:dict];
		self.title = [self objectOrNilForKey:kCountryTitle fromDictionary:dict];
	}

	return self;
}

- (NSDictionary *)dictionaryRepresentation {
	NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
	[mutableDict setValue:self.countryId forKey:kCountryId];
	[mutableDict setValue:self.title forKey:kCountryTitle];

	return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description {
	return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict {
	id object = [dict objectForKey:aKey];
	return [object isEqual:[NSNull null]] ? nil : object;
}

#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder {
	self = [super init];

	self.countryId = [aDecoder decodeObjectForKey:kCountryId];
	self.title = [aDecoder decodeObjectForKey:kCountryTitle];
	return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
	[aCoder encodeObject:_countryId forKey:kCountryId];
	[aCoder encodeObject:_title forKey:kCountryTitle];
}

@end
